/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.ufjf.posjava.cm.controller.filtro;

import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import javax.naming.Context;
import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

/**
 *
 * @author Filipe
 */
@WebFilter(filterName = "LogFilter", urlPatterns = {"/*"}, dispatcherTypes = {DispatcherType.FORWARD, DispatcherType.ERROR, DispatcherType.REQUEST, DispatcherType.INCLUDE})
public class LogFilter implements Filter {
    private ServletContext context = null;
    
    public void init(FilterConfig config) throws ServletException{
        this.context = config.getServletContext();
    }
       
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain)
            throws IOException, ServletException {
        
        long inicio = System.currentTimeMillis();
        chain.doFilter(request, response);
        long fim = System.currentTimeMillis();
        
        String nome = "";
        if(request instanceof HttpServletRequest){
            nome = ((HttpServletRequest)request).getRequestURI();
        }
        context.log(nome + ": " +(fim - inicio) + "ms");
    }

    @Override
    public void destroy() {
    }   
}

 